package com.cooper.mediadb.online;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.util.Log;

import com.cooper.scraper.DownloadException;
import com.cooper.scraper.HttpDownload;
import com.cooper.scraper.ScraperException;

public class AnalyzeQIYI extends AnalyzeVideo {

	public AnalyzeQIYI(HttpDownload httpDownload, String url, String format) {
		super(httpDownload, url, format);
	}

	public AnalyzeQIYI(HttpDownload httpDownload,String format) {
		super(httpDownload, format);
	}

	private String currentVedioID = null;

	public String getCurrentVedioID() {
		return currentVedioID;
	}

	public void setCurrentVedioID(String currentVedioID) {
		this.currentVedioID = currentVedioID;
	}

	private String generateCacheUrl(String vedioId, String pid, String ptype) {
		String result = "http://cache.video.qiyi.com/v/" + vedioId;
		if (pid != null && !"".equals(pid) && ptype != null
				&& !"".equals(ptype)) {
			result += "/" + pid + "/" + ptype + "/";
		}
		return result;
	}
	
	private List<String> analyzeVideo(String pid, String ptype, String tvId)
			throws DownloadException, ScraperException, IOException {
		List<String> result = new ArrayList<String>();
		if (!httpDownload.getParams().isCancelled() && currentVedioID != null
				&& !"".equals(currentVedioID)) {
			String nextUrl = generateCacheUrl(currentVedioID, pid, ptype);
			String page = httpDownload.downloadPage(nextUrl, false);
			if (!httpDownload.getParams().isCancelled()) {
				Map<String, String> allVedios = getFormatsVedio(page);
				if (!allVedios.isEmpty()
						&& !httpDownload.getParams().isCancelled()) {
					String selectVedioId = getSelectFormatVideoId(allVedios);
					if (selectVedioId != null
							&& !selectVedioId.equals(currentVedioID)
							&& !Thread.currentThread().isInterrupted()) {
						nextUrl = generateCacheUrl(selectVedioId, pid, ptype);
						page = httpDownload.downloadPage(nextUrl, false);
					}
					if (!httpDownload.getParams().isCancelled()) {
						if (Pattern
								.compile(
										"<file>http://data\\.video\\.qiyi\\.com/videos/([^/]+)/(.+?)</file>")
								.matcher(page).find()) {
							result = getVedioUri(page);
						} else {
							result = getVedioUri(page, selectVedioId, tvId);
						}

					}
				}
			}

		}
		return result;
	}

	@Override
	public List<String> analyzeVideo() throws DownloadException,
			ScraperException, IOException {

		if (url != null && !"".equals(url)) {
			String page = httpDownload.downloadPage(url);

			if (!httpDownload.getParams().isCancelled()) {
				// String nextUrl = null;

				String pid = null;
				String ptype = null;
				Pattern p = Pattern
						.compile("pid[^:]*:[^\"]*\"(\\d+)\",.*?ptype[^:]*:[^\"]*\"(\\d+)\",.*?videoId[^:]*:[^\"]*\"([^\"]+)\",");
				Matcher m = p.matcher(page);
				if (m.find()) {
					currentVedioID = m.group(3).trim();
					pid = m.group(1).trim();
					ptype = m.group(2).trim();
					// nextUrl = "http://cache.video.qiyi.com/v/" +
					// currentVedioID
					// + "/" + pid + "/" + ptype + "/";
				}
				String tvId = null;
				m = Pattern.compile(",\"tvId\":\"([^\"]+)\"").matcher(page);
				if (m.find()) {
					tvId = m.group(1);
				}
				return analyzeVideo(pid, ptype, tvId);
			}
		}else {
			return analyzeVideo(null,null,null);
		}
		return new ArrayList<String>(0);

	}

	private Map<String, String> getFormatsVedio(String page) {
		Map<String, String> result = new HashMap<String, String>();
		Pattern p = Pattern.compile("<data version=\"(\\d+)\">([^<]+)</data>");
		Matcher m = p.matcher(page);
		while (m.find()) {
			String returnFormat = null;
			switch (Integer.valueOf(m.group(1))) {
			case 96:
				returnFormat = MediaSrcMgr.FORMAT_NORMAL;
				break;
			case 1:
				returnFormat = MediaSrcMgr.FORMAT_REAL;
				break;
			case 2:
				returnFormat = MediaSrcMgr.FORMAT_HIGH;
				break;
			case 3:
				returnFormat = MediaSrcMgr.FORMAT_SUPER;
				break;
			}
			if (returnFormat != null)
				result.put(returnFormat, m.group(2));
		}
		return result;
	}

	private final String BASE_URL_1 = "http://qiyi.soooner.com/videos2/";
	private final String BASE_URL_2 = "http://qiyi.soooner.com/videos/";

	private List<String> getVedioUri(String page, String videoId, String tvId)
			throws ScraperException, DownloadException, IOException {
		if (tvId == null) {
			tvId = "0";
		}
		List<String> result = new ArrayList<String>();
		Pattern p = Pattern
				.compile("<file>(http://f\\.video\\.qiyi\\.com/videos/[^/]+/.+?)</file>");
		Matcher m = p.matcher(page);
		String nextUrl = null;
		if (m.find()) {
			nextUrl = m.group(1);
		}
		if (nextUrl != null) {
			String playPage = httpDownload.downloadPage(nextUrl, false);
			String key = null;
			String videoDir = null;
			m = Pattern.compile("http://[^/]*/([^/]*)/.*?\\?key=(\\w+)")
					.matcher(playPage);
			if (m.find()) {
				videoDir = m.group(1);
				key = m.group(2);
			}
			if (videoDir != null && key != null) {
				playPage = httpDownload.downloadPage(
						"http://cache.video.qiyi.com/vd/" + tvId + "/"
								+ videoId + "/", false);
				String blockReg = "\\{\"duration\".*?\"vid\":\"" + videoId
						+ "\".*?:\\s*\\[\\{.*?:\\s*\\[([^\\]]*\\]\\})";
				m = Pattern.compile(blockReg).matcher(playPage);
				String temp = null;
				if (m.find()) {
					temp = m.group(1);
				}
				if (temp != null) {
					m = Pattern.compile("\\{\"l\":\"([^\"]+)\",[^\\}]*\\}")
							.matcher(temp);
					while (m.find()) {
						result.add("http://qiyi.soooner.com/" + videoDir
								+ m.group(1) + "?key=" + key);
					}
				}
			}
		}
		return result;
	}

	private List<String> getVedioUri(String page) throws ScraperException,
			DownloadException, IOException {
		List<String> resultUrlParam = new ArrayList<String>();
		Pattern p = Pattern
				.compile("<file>http://data\\.video\\.qiyi\\.com/videos/([^/]+)/(.+?)</file>");
		Matcher m = p.matcher(page);
		while (m.find()) {
			resultUrlParam.add(m.group(1) + "/" + m.group(2));
		}
		if (!resultUrlParam.isEmpty()) {
			String baseUrl;
			Map<String, String> header = httpDownload
					.createDefaultHeadersProperty(BASE_URL_1
							+ resultUrlParam.get(0));
			header.put("Content-type", "video/mpeg");
			try {
				header.put("Referer", BASE_URL_1 + resultUrlParam.get(0));

				if (httpDownload.urlExists(BASE_URL_1 + resultUrlParam.get(0),
						header)) {
					baseUrl = BASE_URL_1;
				} else {
					baseUrl = BASE_URL_2;
				}
			} catch (MalformedURLException e) {
				header.put("Referer", BASE_URL_2 + resultUrlParam.get(0));
				if (httpDownload.urlCanUse(BASE_URL_2 + resultUrlParam.get(0),
						header)) {
					baseUrl = BASE_URL_2;
				} else
					throw new ScraperException(e);
			} catch (IOException e) {
				header.put("Referer", BASE_URL_2 + resultUrlParam.get(0));
				Log.d("AnalyzeQiye", "ioE");
				if (httpDownload.urlCanUse(BASE_URL_2 + resultUrlParam.get(0),
						header)) {
					baseUrl = BASE_URL_2;
				} else {
					throw e;
				}
			} catch (DownloadException e) {
				header.put("Referer", BASE_URL_2 + resultUrlParam.get(0));
				if (httpDownload.urlCanUse(BASE_URL_2 + resultUrlParam.get(0),
						header)) {
					baseUrl = BASE_URL_2;
				} else
					throw e;
			}
			List<String> result = new ArrayList<String>();
			for (String s : resultUrlParam) {
				result.add(httpDownload.getRedirectUrl(baseUrl + s));
			}
			return result;
		} else
			return resultUrlParam;
	}

}
